import Dialog from "rc-dialog";
import Button from "../Button";
import React from "react";
import type { ConfirmModalProps } from "./type";

export default Modal;

function Modal(props: ConfirmModalProps) {
  const {
    visible,
    icon,
    title,
    content,
    showCancel = true,
    okText = "确认",
    cancelText = "取消",
    onCancel,
    onOk,
    afterClose,
    close,
  } = props;

  return (
    <Dialog
      visible={visible}
      afterClose={afterClose}
      prefixCls="ct0-modal"
      closable={false}
      transitionName="ct0-modal-zoom"
      maskTransitionName="ct0-modal-fade"
    >
      <div className="ct0-modal-confirm-body-wrapper">
        <div className="ct0-modal-confirm-body">
          {icon ? icon : <DefaultIcon />}
          {title === undefined ? null : (
            <span className="ct0-modal-confirm-title">{props.title}</span>
          )}
          <div className="ct0-modal-confirm-content">{content}</div>
        </div>
        <div className="ct0-modal-confirm-btns">
          {showCancel && (
            <ActionButton actionFn={onCancel} closeModal={close}>
              {cancelText}
            </ActionButton>
          )}
          <ActionButton type="blue" actionFn={onOk} closeModal={close}>
            {okText}
          </ActionButton>
        </div>
      </div>
    </Dialog>
  );
}

interface ActionButtonProps {
  type?: "blue" | "red" | "default";
  closeModal: () => void;
  actionFn?: () => void;
  children?: React.ReactNode;
}

function ActionButton({
  type,
  actionFn,
  closeModal,
  children,
}: ActionButtonProps) {
  const handlePromiseOnOk = (returnValueOfOnOk?: PromiseLike<any>) => {
    if (!returnValueOfOnOk || !returnValueOfOnOk.then) {
      return;
    }
    returnValueOfOnOk.then(
      () => {
        closeModal();
      },
      (e: Error) => {
        console.error(e);
      }
    );
  };

  const handleClick = () => {
    if (!actionFn) {
      closeModal();
      return;
    }
    const returnValueOfOnOk: any = actionFn();
    if (!returnValueOfOnOk) {
      closeModal();
      return;
    }
    handlePromiseOnOk(returnValueOfOnOk);
  };

  return (
    <Button type={type} onClick={handleClick}>
      {children}
    </Button>
  );
}

function DefaultIcon() {
  return (
    <i className="ct0-modal-confirm-icon">
      <svg
        className="ct0-modal-confirm-icon-svg"
        viewBox="0 0 1024 1024"
        fill="currentColor"
      >
        <path d="M509.952 0C228.352 0 0 228.352 0 509.952s228.352 509.952 509.952 509.952 509.952-228.352 509.952-509.952S791.552 0 509.952 0z m0 793.088c-31.232 0-56.832-25.088-56.832-56.832 0-31.232 25.088-56.832 56.832-56.832 31.232 0 56.832 25.088 56.832 56.832 0 31.232-25.6 56.832-56.832 56.832z m28.16-229.376c0 31.232-12.8 56.32-28.16 56.32s-28.16-25.088-28.16-56.32L453.632 312.32c0-31.232 25.088-56.832 56.832-56.832 31.232 0 56.832 25.088 56.832 56.832l-29.184 251.392z" />
      </svg>
    </i>
  );
}
